
var marker;
var infoBubble;

var chatScroll;
//var maxScroll=0;

var scrollBottom=true;

$(function(){
//	$("body").append('<div data-role="popup" id="uploadOptions" data-url="uploadOptions">'
//		+ '<div data-role="content">'
//		+	'<h1>Opciones</h1>'
//		+	'<a href="#" data-role="button" onclick="doChat()" data-theme="b">Chat</a>'
//		+	'<a href="#" data-role="button" onclick="doBuscar()" data-theme="b">Buscar</a>'
//		+	'<a href="imagegallery.html" data-rel="back" data-role="button" data-transition="pop" data-direction="reverse">Cancelar</a>'
//		+ '</div></div>');
});


function doChat() {
	
	scrollBottom=true;
	//clearTimeout(watchChat);
	
//	if(chatId.indexOf("__activity")>-1) {
//		
//		chatNick=$('#selectmenu1').find('option:selected').text();
//		chatId="__activity_" + $('#selectmenu1').val();
//	}
	
//	if($("#chatHeader").text().indexOf(chatNick)>-1 && $("#chatHeader").text().length==chatNick.length + 9) {
//		alert("same chat");
	if(chatId==chatIdAux) {
		//samechat
	} else {
		chatNick=chatNickAux;
		chatId=chatIdAux;
		$("#chatHeader").text("Chat con " + chatNick);	
		lastPeticionId=-1;
		$(".conversation blockquote").remove();
	}

}


$(function(){

  // updateContactList();
   
});

var conversationSelector = '.conversation';
var quoteSelector        = 'blockquote';
var indentSizeInEm       = 2;

function updateContactList(data){
	
	
		$( ".conversation" ).find(".local").remove();
		$("#chatTemplate").tmpl(data).appendTo( ".conversation" );
		lastPeticionId=$("blockquote").last().attr("bid");
		if(!lastPeticionId) lastPeticionId=-1;
		

	
		//$("html, body").animate({ scrollTop: $(document).height() }, "slow");
		
		

		//$(".lastquote").remove();
		//$(".conversation").append('<blockquote bid=' + lastPeticionId + ' class="lastquote"/>');
		//chatScroll.refresh();
		//chatScroll.scrollToElement('.lastquote', 100);

		
		//$( '#idConvContent' ).trigger( 'updatelayout' );
		
    $(conversationSelector).each(function(){
        var classes = {};
        var convo = $(this);
        convo.find(quoteSelector).each(function(){
            // Assumes each quote will have only one class!
            classes[this.className] = true;
        });
        var sortedClasses = [];
        for (var className in classes){
            sortedClasses.push(className);
        };
        var convoPeople = sortedClasses.length;
        sortedClasses.sort();
        $.each(sortedClasses,function(i){
            var options = {
                marginLeft : indentSizeInEm*i+'em',
                marginRight: indentSizeInEm*(convoPeople-i-1)+'em'
            };
            convo.find("."+this).css(options);
        });
    });
    
    $("#idConvContent").getNiceScroll().resize();
    //$("#idConvContent").css("height","315");
    //alert($("#idConvContent").css("height"));
   

    var h=parseInt($(window).height());
    $("#idConvContent").height(parseInt(h - 210));
    


    //alert(scrollBottom + ", " + $("#idConvContent").scrollTop() + ", " + $('#idConvContent').get(0).scrollHeight + ", " + $("#idConvContent").height());
    if(scrollBottom) {
    	
    	//if($("#idConvContent").scrollTop() > maxScroll) maxScroll = ("#idConvContent").scrollTop();
		//alert($("#idConvContent").scrollTop() + ", " + $('#idConvContent').get(0).scrollHeight + ", " + $("#idConvContent").height());
    	
    	//$('#log').append($("#idConvContent").scrollTop() + ", " + $('#idConvContent').get(0).scrollHeight + ", " + $("#idConvContent").height());
    	
		$('#idConvContent').animate({
		    scrollTop: $('#idConvContent').get(0).scrollHeight
		}, 1500);
		

	}
    
    //if(hayMsg) {
    	setChatLeido();
    //}
    
    //$('#idConvContent').getNiceScroll().resize();

    
    //    
//	$('#idConvContent').scroll(function() {
//		  alert("scrolling");
//		});
}

(function ($) {
    $.mobiscroll.i18n.es = $.extend($.mobiscroll.i18n.es, {
        dateFormat: 'dd/mm/yy',
        dateOrder: 'ddmmyy',
        dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
        dayNamesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
        dayText: 'Día',
        hourText: 'Hora',
        minuteText: 'Minutos',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        monthText: 'Mes',
        secText: 'Segundos',
        timeFormat: 'HH:ii',
        timeWheels: 'HHii',
        yearText: 'Año',
        setText: 'OK',
        cancelText: 'Cancelar'
    });
})(jQuery);


$(function () {

            var opt = {

            }

        	var d=new Date();
        	var df= (d.getDate()<10?"0":"") + d.getDate() + "/" + (d.getMonth()<9?"0":"") + (d.getMonth()+1) + "/" + d.getFullYear() + " " + (d.getHours()<10?"0":"") + d.getHours() + ":" + (d.getMinutes()<10?"0":"") + d.getMinutes();
            
            opt.date = {preset : 'date'};
	opt.datetime = { preset : 'datetime', minDate: new Date(), maxDate: new Date(d.getFullYear() + 1, d.getMonth() + 1,d.getDate(),23,55), stepMinute: 5  };
	opt.time = {preset : 'time'};

                $('#hora_inicio').val(df).scroller('destroy').scroller($.extend(opt['datetime'], { theme: 'default', mode: 'scroller', display: 'inline', lang: 'es' }));

                $('#hora_fin').val(df).scroller('destroy').scroller($.extend(opt['datetime'], { theme: 'default', mode: 'scroller', display: 'inline', lang: 'es' }));

        });


function prepareMapClick(location) {
	
	 marker = new google.maps.Marker({
        map: map,
        position: location,
        draggable: true
      });
	
    var contentString = '<div id="content" style="color:black;">'+
    '<h1>Uluru</h1>'+
    '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) '+
    'south west of the nearest large town, Alice Springs; 450&#160;km '+
    '(280&#160;mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.</p>'+
    '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
    'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
    '(last visited June 22, 2009).</p>'+
    '</div>';

     infoBubble = new InfoBubble({
    	 shadowStyle: 1,
         padding: 10, 
         borderRadius: 10,
         borderWidth: 1, 
         borderColor: '#ccc',	 
         backgroundColor: '#fff',
         maxWidth: 200, 
         maxHeight: 100,
         minWidth: 100,
         minHeight: 100,
         arrowSize: 15, 
         arrowPosition: 50,
         arrowStyle: 0 
    });

    var infoBubble2 = new InfoBubble({
      map: map,
      content: '<div style="color:black; overflow:hidden" class="phoneytext">Some label</div>',
      position: location,
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 4,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'phoney',
      arrowStyle: 2,
      overflow: 'hidden'
    });

    infoBubble.open(map, marker);
    //infoBubble2.open();

    var contentTab =                  '<div style="color:black;" data-role="collapsible-set">' +
    '<div data-role="collapsible" data-collapsed="false">' +

        'Coloque el marcador en el lugar de la quedada y confirme para completar más datos' +

    '<div data-role="fieldcontain">' +
        '<fieldset data-role="controlgroup">' +
        '<a id="onButton" data-role="button" href="javascript:addEvento()" class="ui-btn-left" style="color:green">' +
        'Confirmar posición' +
        '</a>' +  
        '</fieldset>' +
    '</div>';
	

    infoBubble.addTab('Evento', contentTab);
    //infoBubble.addTab('Uluru', contentString);

    google.maps.event.addListener(marker, 'click', function() {
      if (!infoBubble.isOpen()) {
        infoBubble.open(map, marker);
      }
    });
	
}




function prepareFirstPositionClick(location) {
	
	marker = new google.maps.Marker({
        map: map,
        position: location,
        draggable: true
      });
	
    

     infoBubble = new InfoBubble({
    	 shadowStyle: 1,
         padding: 10, 
         borderRadius: 10,
         borderWidth: 1, 
         borderColor: '#ccc',	 
         backgroundColor: '#fff',
         maxWidth: 200, 
         maxHeight: 100,
         minWidth: 100,
         minHeight: 100,
         arrowSize: 15, 
         arrowPosition: 50,
         arrowStyle: 0 
    });


    infoBubble.open(map, marker);
    //infoBubble2.open();

    var contentTab =                  '<div id="content" style="width: 200px; color:black;">' +
    

        'Por favor, coloca el marcador en la ubicación para la que deseas realizar búsquedas en su entorno y confirma después con este botón' +

    '<div data-role="fieldcontain">' +
        '<fieldset data-role="controlgroup">' +
        '<a id="onButton" data-role="button" href="javascript:getFirstPosition()" class="ui-btn-left" style="color:green">' +
        'Confirmar posición' +
        '</a>' +  
        '</fieldset>' +
    '</div>' +
 '</div>';
	

    infoBubble.addTab('Mi ubicación', contentTab);
    //infoBubble.addTab('Uluru', contentString);

    google.maps.event.addListener(marker, 'click', function() {
      if (!infoBubble.isOpen()) {
        infoBubble.open(map, marker);
      }
    });
	
}






var evento_lat;
var evento_lon;

function addEvento() {
	
	addPosition();
	$.mobile.changePage($('#page3'));
}

function getFirstPosition() {
	   
	evento_lat=marker.getPosition().lat();
	evento_lon=marker.getPosition().lng();
	   		

	var posicion = {"lon":evento_lon,"lat":evento_lat,"acu":-1};

	getNFm(posicion);
}


function addPosition() {
	evento_lat=marker.getPosition().lat();
	evento_lon=marker.getPosition().lng();
	infoBubble.close();
	marker.setMap(null);
	marker=null;	
}

var editMode=false;
var controlText;

function HomeControl(controlDiv, map) {

	  // Set CSS styles for the DIV containing the control
	  // Setting padding to 5 px will offset the control
	  // from the edge of the map.
	  controlDiv.style.padding = '5px';

	  // Set CSS for the control border.
	  var controlUI = document.createElement('div');
	  controlUI.style.backgroundColor = 'white';
	  controlUI.style.borderStyle = 'solid';
	  controlUI.style.borderWidth = '2px';
	  controlUI.style.color = 'black';	  
	  controlUI.style.cursor = 'pointer';
	  controlUI.style.textAlign = 'center';
	  controlUI.title = 'Click to set event place';
	  controlDiv.appendChild(controlUI);

	  // Set CSS for the control interior.
	  controlText = document.createElement('div');
	  controlText.style.fontFamily = 'Arial,sans-serif';
	  controlText.style.fontSize = '12px';
	  controlText.style.paddingLeft = '4px';
	  controlText.style.paddingRight = '4px';
	  controlText.innerHTML = '<strong>' + $.i18n._('create_event') + '</strong>';
	  controlUI.appendChild(controlText);

	  // Setup the click event listeners: simply set the map to Chicago.
	  google.maps.event.addDomListener(controlUI, 'click', function() {
		idSeguimiento=null;
	    editMode=!editMode;
	    if(editMode) { 
	    	controlText.innerHTML = '<strong>' + $.i18n._('editing_event') + '</strong>';
	    	if(infoBubble) infoBubble.close();
	    	if(marker) {
	    		marker.setMap(null);
	    		marker=null;
	    	}
	    	
	    }
	    else controlText.innerHTML = '<strong>' + $.i18n._('create_event') + '</strong>';
	  });
}



function getEvents() {
	var d=new Date();
	var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

	$.getJSON(getUrl() + "getEvents?activity=" + $(selectmenu1).val() + "&mode=0.1.11&df=" + df, function(data){ 	
		
	});
	
}

function aceptarEvento() {
	
	createEvent=true;
	
	if(googleOn) geocoder.geocode({'latLng': new  google.maps.LatLng(evento_lat,evento_lon)}, makeGeocode(evento_lon,evento_lat,5));
	
	else {
	
		var d=new Date();
	
	    $.ajax({
		 url:  getUrl() +  'setEvent',
		data:{ deviceId: deviceId + df, activity: $(selectmenu1).val(), name : 'evento' + d.getMinutes() + ":" + d.getSeconds(), comment: 'fecha', color : '0000FF'	, abbr: '*', 
				latency: '20000', refresh: '3000', mode: '0.1.11',
				start: $(hora_inicio).val(),
				end: $(hora_fin).val(),
				lat: evento_lat,
				lon: evento_lon,
				df: d.getTime()
			},
		 success: function(result) {
				showAlert("Evento","Evento creado");
				$.mobile.changePage($('#page1'));	
			  },
		 async:   false
	    });
	}

}


function sendReceiveChat() {
		
	
	var txt=$("#miTextoChat").val();
	
	//clearTimeout(watchChat);
	
	if(txt!=null && txt!="") {
		var d=new Date();
		var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	
	
		$("#miTextoChat").val("");
		
	 	$.post(getUrl() + 'setPeticion',
			{       remiteId : deviceId, 
					destinoId : chatId,
					texto: txt,
					confirmar: false,
					time: df
			}
	 	);
	 	
	 	scrollBottom=true;
	 	//getChat();
	 	
		var chat={
			nick: config.nick, 
			color: config.color, 
			texto: txt				
		};
		
		$("#chatOwnText").tmpl(chat).appendTo( ".conversation" );
		$('#idConvContent').animate({
		    scrollTop: $('#idConvContent').get(0).scrollHeight
		}, 1500);
		
		watchChat=setTimeout(function(){getChat()},2000);	
		showContacts();
	
	}
}


function refreshChat(ids) { 
	
    //alert("mensaje de " + ids);
	if(currPage="#page4" && $.mobile.activePage.is("#page4") && ids.indexOf(chatId)!=-1) { 
		hayMsg=true;
		getChat();		
	} 
	else {
		if(currPage!="#pageContactos") { 
			goPage("pageContactos",true);
		}
		showContacts();
	}
}

function getChat() {
	

	clearTimeout(watchChat);
	
	var d=new Date();
	var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

	if(lastPeticionId>0) {
		
		$.get(getUrl() + 'getChatId',
	 			{       destinoId : deviceId,
	 					remiteId : chatId,
	 					id: lastPeticionId,
	 					time: df
	 			},
	 			function(data){
	 				updateChat(data);
	 			}

		);
		
	} else {
		lastDate=null;
     	$.get(getUrl() + 'getChat',
     			{       destinoId : deviceId,
						remiteId : chatId,
						time: df
     			},
     			function(data){
     				updateChat(data);
     			}

		);
	
	}
}

function setChatLeido() {
	
	var d=new Date();

	if(jf) { 
		jf.cleanNotification();
		hayMsg=false; 
		setTimeout(function(){showContacts()},2000);	

		
	}
		
		$.get(getUrl() + 'setContactoLeido',
	 			{       lectorId : deviceId,
	 					leidoId : chatId,
	 					time: d.getTime()
	 			},
	 			function(data){
	 				alert("mensajes leidos");
	 			}

		);
		


}



function updateChat(data) {
		updateContactList(data);
		//watchChat=setTimeout(function(){getChat()},15000);
}


var curPage=false;

function goPage(page,go) {
	

	//alert(page);
	//if(navigator && navigator.notification) navigator.notification.vibrate(300);
//	var newPageTab= '.' + page + 'Tab';
//	$(newPageTab).addClass("ui-btn-active");
//	$(newPageTab).addClass("ui-state-persist");
//	
	
//	scrollBottom=true;
	//clearTimeout(watchChat);


	
	if(page=="page4") doChat();
//	else if(page=="page2") 	{
//		//clearOverlays();
//		//getMarkers(people,paint);
//	}

	//$.mobile.changePage($('#page4'), 'slide');
	
//	curPage=false;
	if(go) $.mobile.changePage($('#' + page));
}

function postGoPage(page) {
	
	var newPageTab= '.' + page + 'Tab';
	$(newPageTab).addClass("ui-btn-active");
	$(newPageTab).addClass("ui-state-persist");
	
	
	//while(!($.mobile.activePage.attr('id')==page && curPage)) $.mobile.changePage($('#' + page), 'none');
		
		

	var oldPageTab= '.page1Tab';
	$(oldPageTab).removeClass("ui-btn-active");
	$(oldPageTab).removeClass("ui-state-persist");
	oldPageTab= '.page2Tab';
	$(oldPageTab).removeClass("ui-btn-active");
	$(oldPageTab).removeClass("ui-state-persist");
	oldPageTab= '.page4Tab';
	$(oldPageTab).removeClass("ui-btn-active");
	$(oldPageTab).removeClass("ui-state-persist");
	oldPageTab= '.page10Tab';
	$(oldPageTab).removeClass("ui-btn-active");
	$(oldPageTab).removeClass("ui-state-persist");	

	//alert("quito de " + oldPageTab);

	
	$(newPageTab).addClass("ui-btn-active");
	$(newPageTab).addClass("ui-state-persist");
	
	//$(oldPageTab).removeClass("ui-btn-active");
	//$(oldPageTab).removeClass("ui-state-persist");

	//alert("pongo a " + newPageTab);
			
}

function filterChat(texto, nick) {
	if(texto.indexOf("__")>-1) {
		if(texto=="__0") texto="<quiero ir tu encuentro>";
		else if(texto=="__1") texto="<te espero en mi posición>";
		else if(texto=="__2") texto="<lo siento, no te puedo esperar>";
		else if(texto=="__3") texto="<mejor sígueme, voy despacio>";
		else if(texto=="__11") texto="<me apunto al evento>";
		else if(texto=="__12") texto="<ya he llegado al evento>";
		else if(texto=="__20") texto="<contacto mapeado desde la agenda>";
		else if(texto=="__30") texto="<añadido al grupo>";
	}	
	return texto;
}





function showContacts(bloqueados) {
	
	
	var df=new Date();
	
    $("#contactosRecientes li").remove();
    $("#contactosRecientes").append('<li>cargando...</li>');
    
    if ($("#contactosRecientes").hasClass('ui-listview')) {
    	$("#contactosRecientes").listview().listview("refresh");
    } else {
    	$("#contactosRecientes").trigger("create");
    }
    
//    $("#contactosRecientes").listview().listview("refresh");
	
    var path="getContactos";
    if(bloqueados) path="getContactosBlocked";
    
	$.ajax({ 
		  url: getUrl() + path, 
		  dataType: 'json', 
		  data: { deviceId: deviceId, time: df.getTime()}, 
		  success: function(data){ 					
			  if(data!=null) paintContacts(data);
		  }
//		  , 
//		  timeout: 5000, 
//		  error: function(jqXHR, status, errorThrown){  
//	
//		  } 
		}); 
}

function paintContacts(contacto) {
	
    $("#contactosRecientes li").remove();
    
    if(contacto.length==0) $("#contactosRecientes").append("<li>lista de contactos vacía</li>");
    
    
    for (i = 0; i < contacto.length; i++) {  
		
    	var alias="";

    	
    	var people=contacto[i].contactoA;
    	var hasMsgs=contacto[i].atoB;
    	var blocked=contacto[i].blockedBtoA;
    	if(contacto[i].aalias!=null && contacto[i].aalias!="") alias=" (" + contacto[i].aalias + ")";
    	
    	if(people.deviceId==deviceId) {
    		people=contacto[i].contactoB;
    		hasMsgs=contacto[i].btoA;
    		blocked=contacto[i].blockedAtoB;
        	if(contacto[i].balias!=null && contacto[i].bAlias!="") alias=" (" + contacto[i].balias + ")";
    	}
    	
    	var newMsgs="";
    	if(hasMsgs) newMsgs="sin leer";
    	if(blocked==2) newMsgs="bloqueado";
    	if(blocked==1) newMsgs+=" (silenciado)";
    		
    	var selector="#selectmenu1 option[value='" + people.activity + "']";
    	
    	
    	var activity='<p>en ' + $(selector).text() + ' ' + $.i18n._('time_ago', [msToDHM(new Date().getTime() - parseFloat(people.online))]) + '</p>'; 
    	if(people.deviceId.indexOf("__activity")>-1) {
    		activity="<p>Actividad principal<p>";
    		people.nick=$(selector).text();
    	}  else if( people.deviceId.indexOf("__event")>-1) {
    		activity="<p>Evento en " + $(selector).text() + "</p>";
    	}
    	
 
    	
    	var userdata='<li class="mapAll" chatId="' + people.deviceId + '" lat="' + people.lat +'" lon="' + people.lon + '" zoom="15" data-theme="c">' +  	
	    '<h2>' + people.nick + alias + '</h2>' +
	    activity +
	    '<p><strong>último contacto</strong> ' + $.i18n._('time_ago', [msToDHM(new Date().getTime() - parseFloat(contacto[i].hora))]) + '</p>' +
	    '<fieldset data-role="controlgroup" data-type="horizontal"><input  chatId="' + people.deviceId + '" class="custom" type="checkbox"  name="check_'+people.nick+'" id="check_'+ people.nick +'"/><label  data-theme="c" for="check_'+ people.nick + '">Seleccionar</label></fieldset>' + 
	    '<p class="ui-li-aside"><strong><span style="color:red">' + newMsgs + '</span></strong></p>' +							    
	    '</li>'
		
	    $("#contactosRecientes").append(userdata);
    }
    if ($("#contactosRecientes").hasClass('ui-listview')) {
    	$("#contactosRecientes").listview().listview("refresh");
    } else {
    	$("#contactosRecientes").trigger("create");
    }

    //$('input[data-type="search"]').trigger("change");
$('#idColSet2 input[data-type="search"]').val("");
}



function showIntegrantes(bloqueados) {
	
	
	var df=new Date();
	
    $("#integrantes li").remove();
    $("#integrantes").append('<li>cargando...</li>');
    
    if ($("#integrantes").hasClass('ui-listview')) {
    	$("#integrantes").listview().listview("refresh");
    } else {
    	$("#integrantes").trigger("create");
    }
    
//    $("#contactosRecientes").listview().listview("refresh");
	
    var path="getContactos";
    if(bloqueados) path="getContactosBlocked";
    
	$.ajax({ 
		  url: getUrl() + path, 
		  dataType: 'json', 
		  data: { deviceId: chatId, time: df.getTime()}, 
		  success: function(data){ 					
			  if(data!=null) paintIntegrantes(data);
		  }
//		  , 
//		  timeout: 5000, 
//		  error: function(jqXHR, status, errorThrown){  
//	
//		  } 
		}); 
}

function paintIntegrantes(contacto) {
	
    $("#integrantes li").remove();
    
    if(contacto.length==0) $("#integrantes").append("<li>lista de miembros vacía</li>");
    
    
    for (i = 0; i < contacto.length; i++) {  
		
    	var alias="";
    	
    	var people=contacto[i].contactoA;
    	var hasMsgs=contacto[i].atoB;
    	var blocked=contacto[i].blockedBtoA;
    	if(contacto[i].aalias!=null && contacto[i].aalias!="") alias=" (" + contacto[i].aalias + ")";

    	
    	if(people.deviceId==chatId) {
    		people=contacto[i].contactoB;
    		hasMsgs=contacto[i].btoA;
    		blocked=contacto[i].blockedAtoB;
        	if(contacto[i].balias!=null && contacto[i].balias!="") alias=" (" + contacto[i].balias + ")";
    	}
    	
//    	var newMsgs="";
//    	if(hasMsgs) newMsgs="sin leer";
//    	if(blocked==2) newMsgs="bloqueado";
//    	if(blocked==1) newMsgs+=" (silenciado)";
//    		
    	var selector="#selectmenu1 option[value='" + people.activity + "']";
    	
    	
    	var activity='<p>en ' + $(selector).text() + ' ' + $.i18n._('time_ago', [msToDHM(new Date().getTime() - parseFloat(people.online))]) + '</p>'; 
    	if(people.deviceId.indexOf("__activity")>-1) {
    		activity="<p>Actividad principal<p>";
    		people.nick=$(selector).text();
    	}  else if( people.deviceId.indexOf("__event")>-1) {
    		activity="<p>Evento en " + $(selector).text() + "</p>";
    	}
    	
 
    	
    	var userdata='<li class="mapAll" chatId="' + people.deviceId + '" lat="' + people.lat +'" lon="' + people.lon + '" zoom="15" data-theme="c">' +  	
	    '<h2>' + people.nick + '</h2>' +
	    activity +
	    '<p><strong>último contacto</strong> ' + $.i18n._('time_ago', [msToDHM(new Date().getTime() - parseFloat(contacto[i].hora))]) + '</p>' +
//	    '<p class="ui-li-aside"><strong><span style="color:red">' + newMsgs + '</span></strong></p>' +							    
	    '</li>'
		
	    $("#integrantes").append(userdata);
    }
    if ($("#integrantes").hasClass('ui-listview')) {
    	$("#integrantes").listview().listview("refresh");
    } else {
    	$("#integrantes").trigger("create");
    }

    //$('input[data-type="search"]').trigger("change");
$('#idColIntegrantes input[data-type="search"]').val("");
}

function silenceContact() {
	doContact("setSilenced");
}


function blockContact() {
	doContact("setBlocked");
}


function resetContact() {
	doContact("resetBlocked");
}



function doContact(path) {

	goPage("pageContactos",true);
	
	var df=new Date();
	
	$.ajax({ 
		  url: getUrl() + path, 
		  dataType: 'json', 
		  data: { idA: deviceId, idB: chatId, time: df.getTime()}, 
		  success: function(data){ 					
			 alert(data);
		  }
	}); 
	
	setTimeout(function(){showContacts()},2000);	
}


function createGroup() {

	 var members = new Array();

	 
	 goPage("pageContactos",true);
         
	 $(":checkbox:checked").each(function () {
		 if(deviceId!=$(this).attr('chatId')) members.push($(this).attr('chatId'));
		 this.click(); 
	  });

	if(members.length>1) {
		var df=new Date();
		
		$.ajax({ 
			  url: getUrl() + "addGroup", 
			  dataType: 'json', 
			  data: { deviceId: deviceId,
				  	  members: members,
				  	  time: df.getTime()
				  	}, 
			  success: function(data){ 					
				 alert("Grupo creado con " + (members.length + 1) + " contactos" );
			  }
		});
	} else {		
		alert("Selecciona al menos dos contactos para crear un grupo con ellos");
	}
}

function viewContact() {


	lat=latAux;
	lon=lonAux;
	zoom=zoomAux;

	goPage("page2",true);
	
}


function changeAlias() {


goPage("pageContactos",true);


$(document).simpledialog2({
    mode: 'button',
    headerText: 'Alias',
    headerClose: true,
    buttonPrompt: 'Alias para el contacto ' + chatNickAux,
    buttonInput: true,
    buttons : {
      'OK': {
        click: function () { 
        	
    		var df=new Date();
    		
    		$.ajax({ 
    			  url: getUrl() + "changeAlias", 
    			  dataType: 'json', 
    			  data: { deviceId: deviceId,
    				  	  aliasId: chatIdAux,
    					  alias: $.mobile.sdLastInput,
    				  	  time: df.getTime()
    				  	}, 
    			  success: function(data){ 					
    				 alert(data);
    			  }
    		});	
            alert($.mobile.sdLastInput);
        }
      },
    }
  });
	
}



function showActivities() {
	
	
	var df=new Date();
	
    $("#activitiesListview li").remove();
    $("#activitiesListview").append('<li>cargando...</li>');
    
    if ($("#activitiesListview").hasClass('ui-listview')) {
    	$("#activitiesListview").listview().listview("refresh");
    } else {
    	$("#activitiesListview").trigger("create");
    }
    
	
    var path="getActivitiesCount";
    
	$.ajax({ 
		  url: getUrl() + path, 
		  dataType: 'json', 
		  data: { 	deviceId: deviceId,
			  		mode: '0.1.11',
			  		time: df.getTime()
			  	}, 
		  success: function(data){ 					
			  if(data!=null) paintActivities(data);
		  }

	}); 
}

function paintActivities(act) {
	
    $("#activitiesListview li").remove();
    
    if(act.length==0) $("#activitiesListview").append("<li>Nadie (ni tú) dando posiciones por tu zona</li>");
    
    
    for (i = 0; i < act.length; i++) {  
		
		var selector="#selectmenu1 option[value='" + act[i].activity + "']";
    	var userdata='<li activityId="' + act[i].activity + '" data-theme="c"><a href="#page1">' +  	
	    '<h2>' + $(selector).text() + '</h2></a>' +
	    '<span class="ui-li-count">' + act[i].count + '</span>' +				
		'</li>'
		
	    $("#activitiesListview").append(userdata);
    }
    if ($("#activitiesListview").hasClass('ui-listview')) {
    	$("#activitiesListview").listview().listview("refresh");
    } else {
    	$("#activitiesListview").trigger("create");
    }

    //$('input[data-type="search"]').trigger("change");
    $('#idActivities input[data-type="search"]').val("");
}


function mapContacts() {


	
	
	var options = new ContactFindOptions();
    options.filter=""; 
    options.multiple=true;
    var filter = ["*"];


	if(jf) navigator.contacts.find(filter, onSuccessContacts, onErrorContacts, options);

}



 // onError: Failed to get the contacts
 //
 function onErrorContacts(contactError) {
     alert('onError:' + contactError);
 }
	
 // onSuccess: Get a snapshot of the current contacts
 //
 function onSuccessContacts(contacts) {
     
	 var tlfns = new Array();
	 var names = new Array();

	 for (var i=0; i<contacts.length; i++) {   
		 if(contacts[i].phoneNumbers!=null)	{	 
		 	for(j=0; j<contacts[i].phoneNumbers.length; j++) { 
		 		tlfns.push(contacts[i].phoneNumbers[j].value);
				names.push(contacts[i].name); 
		 	}
		 }
	 }
         
     
 	//var tlfns =  ["666666666", "777777777", "888888888", "999999999"];
	
 
	if(tlfns.length>0) {
		var df=new Date();
		
		$.ajax({ 
			  url: getUrl() + "mapContactos", 
			  dataType: 'json', 
			  data: { deviceId: deviceId,
				  	  tlfns: tlfns,
					  names: names,
				  	  time: df.getTime()
				  	}, 
			  success: function(data){ 					
				 alert(data);
			  }
		});
	}
	
}


